package OrderService

import (
	"context"
	"gdshop-admin-go-api/app/entity"
	"gdshop-admin-go-api/library/response"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
)

func getOrderModel(ctx context.Context, orderId int) *entity.Order {
	var params *entity.Order
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "order").Where("id", orderId).Struct(&params)
	if err != nil {
		return nil
	}

	return params
}
func getOrderAndPriceModel(ctx context.Context, orderId int) *entity.OrderAndPrice {
	var params *entity.OrderAndPrice
	err := toolsDb.GetUnSafaTable(ctx, "order").As("o").Where("o.delete_at < 1 AND o.id = ?",
		orderId,
	).LeftJoin("order_price op", "o.id = op.order_id").Fields(
		"o.*,IFNULL(op.dispatch_price_change,0) AS dispatch_price_change,IFNULL(op.total_price_change,0) AS total_price_change",
	).Struct(&params)
	if err != nil {
		return nil
	}

	return params
}

func GetStatusTextArr() g.MapIntStr {
	return map[int]string{
		0:  "关闭",
		1:  "待付款",
		2:  "待备货",
		3:  "待发货",
		4:  "待收货",
		5:  "待评价",
		99: "已完成",
	}
}

func GetRefundStatusTextArr() g.MapIntStr {
	return map[int]string{
		0:  "正常",
		1:  "待处理",
		2:  "驳回",
		3:  "同意",
		99: "完成",
	}
}

func GiveBackCouponByOrderId(ctx context.Context, orderId int) *response.JsonResponse {
	var oscList []*entity.OrderSubCoupon
	err := toolsDb.GetUnSafaTable(ctx, "order_sub_coupon").
		Where("order_id", orderId).Structs(&oscList)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	if len(oscList) > 0 {
		mcIds := []int{}
		for _, item := range oscList {
			mcIds = append(mcIds, item.MemberCouponId)
		}
		update, err := toolsDb.GetUnSafaTable(ctx, "member_coupon").Where("id IN (?)", mcIds).Update(g.Map{
			"use_time": 0,
		})
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}
		affected, err := update.RowsAffected()
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}
		if int(affected) != len(mcIds) {
			g.Log().Ctx(ctx).Cat("CloseNoPayOrder").Async().Error("退还优惠券出错 orderId:" + gconv.String(orderId))
			return response.FailByRequestMessage(nil, "退还优惠券出错")
		}

		return response.SuccessByRequestMessage(nil, "成功")
	}

	return response.SuccessByRequestMessage(nil, "成功，未使用优惠券")
}
